package com.example.mybatisplusdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.mybatisplusdemo.dao.ProductMapper;
import com.example.mybatisplusdemo.entity.ProductEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hh
 * @since 2023/2/4
 */
@RestController
@RequestMapping("product")
@RequiredArgsConstructor
public class ProductController {

    private final ProductMapper productMapper;

    /**
     * 测试乐观锁
     */
    @PostMapping("purchase")
    public void purchase() {
        LambdaQueryWrapper<ProductEntity> wrapper = Wrappers.lambdaQuery(ProductEntity.class).eq(ProductEntity::getId, 1);
        ProductEntity productA = productMapper.selectOne(wrapper);
        ProductEntity productB = productMapper.selectOne(wrapper);

        Integer id = productB.getId();
        productA.setNum(productA.getNum() - 10);
        productMapper.updateById(productA);

        productB.setNum(productB.getNum() - 10);
        int result = productMapper.updateById(productB);
        if (result == 0) {
            ProductEntity productC = productMapper.selectById(id);
            productC.setNum(productC.getNum() - 20);
            productMapper.updateById(productC);
        }

        ProductEntity newProduct = productMapper.selectById(id);
        System.out.println("当前库存为：" + newProduct.getNum());
    }

}
